﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using LiteLauncher.Pages;
using Microsoft.Win32;

namespace LiteLauncher
{
    public static class AppSettings
    {
        // 配置项定义
        public static string JavaPath
        {
            get => Properties.Settings.Default.JavaPath ?? AutoDetectJavaPath();
            set
            {
                if (File.Exists(value) || value == "java")
                {
                    Properties.Settings.Default.JavaPath = value;
                    SaveSettings();
                }
            }
        }
        public static void ResetMemorySettings()
        {
            MinMemory = 1024;
            MaxMemory = 2048;
        }

        public static void ResetToDefaults()
        {
            JavaPath = AutoDetectJavaPath();
            MinecraftPath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                ".minecraft");
            ResetMemorySettings();
        }
        public static string Username
        {
            get => GetSetting(nameof(Username), "Player");
            set => SetSetting(nameof(Username), value);
        }

        public static int MinMemory
        {
            get => Properties.Settings.Default.MinMemory;
            set => Properties.Settings.Default.MinMemory = value;
        }

        public static int MaxMemory
        {
            get => Properties.Settings.Default.MaxMemory;
            set => Properties.Settings.Default.MaxMemory = value;
        }

        public static string MinecraftPath
        {
            get => GetSetting(nameof(MinecraftPath),
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ".minecraft"));
            set => SetSetting(nameof(MinecraftPath), value);
        }

        // 配置持久化核心方法
        private static T GetSetting<T>(string key, T defaultValue = default)
        {
            try
            {
                var value = Properties.Settings.Default[key];
                return value != null ? (T)value : defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }

        private static void SetSetting<T>(string key, T value)
        {
            Properties.Settings.Default[key] = value;
            SaveSettings();
        }

        // 自动保存（带线程锁）
        private static readonly object _saveLock = new object();
        public static void SaveSettings()
        {
            lock (_saveLock)
            {
                Properties.Settings.Default.Save();
            }
        }

        // Java自动检测逻辑
        public static string AutoDetectJavaPath()
        {
            var detectedPaths = new List<string>();

            // 注册表检测增强
            var regPaths = new[]
            {
        @"SOFTWARE\JavaSoft\Java Runtime Environment",
        @"SOFTWARE\WOW6432Node\JavaSoft\Java Runtime Environment",
        @"SOFTWARE\Eclipse Adoptium\JDK"
    };

            foreach (var keyPath in regPaths)
            {
                var key = Registry.LocalMachine.OpenSubKey(keyPath);
                if (key == null) continue;

                var currentVersion = key.GetValue("CurrentVersion")?.ToString();
                if (string.IsNullOrEmpty(currentVersion)) continue;

                var subKey = key.OpenSubKey(currentVersion);
                var javaHome = subKey?.GetValue("JavaHome")?.ToString();
                if (string.IsNullOrEmpty(javaHome)) continue;

                var javaPath = Path.Combine(javaHome, "bin", "java.exe");
                if (File.Exists(javaPath)) detectedPaths.Add(javaPath);
            }

            // 文件系统搜索优化
            var searchDirs = new[]
            {
        Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
        Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
    };

            foreach (var dir in searchDirs)
            {
                try
                {
                    var javaDirs = Directory.EnumerateDirectories(dir, "Java*")
                        .Concat(Directory.EnumerateDirectories(dir, "JDK*"))
                        .Concat(Directory.EnumerateDirectories(dir, "jdk*"));

                    foreach (var javaDir in javaDirs)
                    {
                        var javaPath = Path.Combine(javaDir, "bin", "java.exe");
                        if (File.Exists(javaPath)) detectedPaths.Add(javaPath);
                    }
                }
                catch (UnauthorizedAccessException) { /* 忽略权限问题 */ }
            }

            // 优先选择最新版本
            return detectedPaths
                .OrderByDescending(p => FileVersionInfo.GetVersionInfo(p).FileVersion)
                .FirstOrDefault() ?? "java";
        }
        // 配置验证
        public static bool ValidateMemory(out string error)
        {
            error = null;

            if (MinMemory <= 0)
            {
                error = "最小内存必须大于0";
                return false;
            }

            if (MaxMemory <= MinMemory)
            {
                error = "最大内存必须大于最小内存";
                return false;
            }

            if (MaxMemory > GetSystemMemoryMB() * 0.8)
            {
                error = "分配内存超过系统可用内存的80%";
                return false;
            }

            return true;
        }

        private static int GetSystemMemoryMB()
        {
            var mc = new System.Management.ManagementClass("Win32_ComputerSystem");
            foreach (System.Management.ManagementObject mo in mc.GetInstances())
            {
                var totalBytes = Convert.ToUInt64(mo["TotalPhysicalMemory"]);
                return (int)(totalBytes / 1024 / 1024);
            }
            return 4096; // 默认4GB
        }
        public interface IMinecraftVersionService
        {
            IEnumerable<MinecraftVersion> GetInstalledVersions();
            MinecraftVersion? GetVersion(string versionId);
        }
    }
}